import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/purchase_quality_problem_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/purchase_quality_problem.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/purchase_quality_problem/purchase_quality_problem_caurse_list.dart';
import 'package:flutter_admin/pages/odoo/purchase_quality_problem/purchase_quality_problem_dialog.dart';
import 'package:flutter_admin/pages/odoo/purchase_quality_problem/purchase_quality_problem_edit.dart';
import 'package:flutter_admin/pages/odoo/purchase_quality_problem/purchase_quality_problem_refuse_list.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/dms_file/dms_file_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class PurchaseQualityProblemList extends StatefulWidget {
  PurchaseQualityProblemList({Key? key}) : super(key: key);

  @override
  _PurchaseQualityProblemListState createState() =>
      _PurchaseQualityProblemListState();
}

class _PurchaseQualityProblemListState
    extends State<PurchaseQualityProblemList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  PurchaseQualityProblem purchaseQualityProblem = PurchaseQualityProblem();
  List<PurchaseQualityProblem> selectedList = [];
  DateFormat format = DateFormat('yyyy-MM-dd');
  UserInfo userInfo = StoreUtil.getCurrentUserInfo();
  String workshopCode = '';

  @override
  void initState() {
    super.initState();
    purchaseQualityProblem.createDateStart = Utils.getDate();
    purchaseQualityProblem.createDateEnd = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    var res = await DynamicDataApi.getModels(
        model: 'hr.department', key: 'id', val: userInfo.deptId);
    if (res.success!) {
      workshopCode = res.data[0]['department_code'];
    }
    // workshopCode = 'ZL';
    /**
     * 
     * 测试账号：
     * 供应商 test1 密码：1.
     * 客户账号：ZT-039400 密码：
     * @Author: chendeji
     * @Date: 2022-05-25 10:06:44
    */
    _query();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 160,
            label: '开始日期',
            value: purchaseQualityProblem.createDateStart,
            lastDate: isNotBlank(purchaseQualityProblem.createDateEnd)
                ? format.parse(purchaseQualityProblem.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              purchaseQualityProblem.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              purchaseQualityProblem.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 160,
            label: '结束日期',
            value: purchaseQualityProblem.createDateEnd,
            firstDate: isNotBlank(purchaseQualityProblem.createDateStart)
                ? format.parse(purchaseQualityProblem.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              purchaseQualityProblem.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              purchaseQualityProblem.createDateEnd = v;
            },
          ),
          CryInput(
            width: 140,
            label: '流水号',
            value: purchaseQualityProblem.serialnumber,
            onSaved: (v) {
              purchaseQualityProblem.serialnumber = v;
            },
          ),
          CryInput(
            width: 140,
            label: '产品名称',
            value: purchaseQualityProblem.productName,
            onSaved: (v) {
              purchaseQualityProblem.productName = v;
            },
          ),
          CryInput(
            width: 140,
            label: '供应单位',
            value: purchaseQualityProblem.supplierName,
            onSaved: (v) {
              purchaseQualityProblem.supplierName = v;
            },
          ),
          CrySelect(
            width: 140,
            label: '状态',
            dataList: [
              SelectOptionVO(value: '', label: ""),
              SelectOptionVO(value: PurchaseQualityProblem.SENDED, label: "提交"),
              SelectOptionVO(
                  value: PurchaseQualityProblem.SUBMIT_CAURSE, label: "已处理"),
            ],
            value: purchaseQualityProblem.status,
            onSaved: (v) {
              purchaseQualityProblem.status = v;
            },
          ),
        ],
      ),
    );
    var formator = DateFormat('yyyy-MM-dd HH:mm:ss');
    ThemeData theme = Theme.of(context);
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        //isDisplayDesktop(context)?DataColumn(
        //  label: Text(S.of(context).operating),
        //):DataColumn(label: Container()),
        DataColumn(
          label: Text('流水号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('文档号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('产品名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('规格型号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('供应单位'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          // label: Text('来料日期'),
          label: Text('检测日期'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          // label: Text('来料日期'),
          label: Text('处理时长'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('来料数量'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('抽检数量'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('不合格数量'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('问题描述'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('检验人'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('处理方式'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('处理人'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('客户原因分析/改进措施'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        // DataColumn(
        //   label: Text('退回意见'),
        //   //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        // ),
        DataColumn(
          label: Text('跟踪情况验证'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('状态'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        // DataColumn(
        //   label: Text('创建人'),
        //   //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        // ),
        DataColumn(
          label: Text('创建时间'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('处理时间'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('采购员'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      choseColor: (m) {
        PurchaseQualityProblem purchaseQualityProblem =
            PurchaseQualityProblem.fromMap(m);
        /**
         * 需要针对数据来设置当行的颜色值
         * 
         * @Author: chendeji
         * @Date: 2022-05-20 09:11:20
        */
        var dealDayCount =
            getDateDiffDayCount(purchaseQualityProblem, formator);
        var color = Colors.green;
        if (dealDayCount > 10) {
          // 超期3天黄色
          color = Colors.yellow;
        }
        if (dealDayCount > 14) {
          // 超期7天蓝色
          color = Colors.blue;
        }
        if (dealDayCount > 21) {
          // 超期14天红色
          color = Colors.red;
        }
        return MaterialStateProperty.resolveWith((states) {
          return color.withOpacity(0.08);
        });
      },
      getCells: (m) {
        PurchaseQualityProblem purchaseQualityProblem =
            PurchaseQualityProblem.fromMap(m);

        /**
             * 根据数据返回，根据数据得到处理时长，
             * 需求：
             * 确认发出后，需要判断是否已经有退回记录
             * > 如果有退回记录，那么从退回记录的时间开始，计算处理时长
             * > 如果没有退回记录，直接查看最近一次的原因分析记录，计算确认发出后的时间差
             * @Author: chendeji
             * @Date: 2022-05-19 15:52:35
            */
        var dealDayCount =
            getDateDiffDayCount(purchaseQualityProblem, formator);
        return [
          DataCell(
              Text(
                purchaseQualityProblem.serialnumber ?? '--',
                style: TextStyle(
                    color: Colors.blue, decoration: TextDecoration.underline),
              ), onTap: () {
            //这里需要做一个点击操作，然后展示一个记录的详情对话框，在对话框中，加入附件上传列表展示的入口，或者直接调用上传附件的功能
            _edit(purchaseQualityProblem, isEditable: false);
          }),
          DataCell(Text(purchaseQualityProblem.bhx ?? '--')),
          DataCell(Text(purchaseQualityProblem.productName ?? '--')),
          DataCell(Text(purchaseQualityProblem.spec ?? '--')),
          DataCell(Text(purchaseQualityProblem.supplierName ?? '--')),
          DataCell(Text(purchaseQualityProblem.jcrq!)),
          /**
           * 一周内处理完成绿色，超期3天黄色，超期7天蓝色，超期14天红色。
           * @Author: chendeji
           * @Date: 2022-05-19 16:08:59
          */
          DataCell(Text(
            dealDayCount > 0 ? '> $dealDayCount天' : '< 1天',
          )),
          DataCell(Text(purchaseQualityProblem.instockqty ?? '--')),
          DataCell(Text(purchaseQualityProblem.checkqty.toString())),
          DataCell(Text(purchaseQualityProblem.unqualifiedqty.toString())),
          DataCell(Text(purchaseQualityProblem.questiondescription ?? '--')),
          DataCell(Text(purchaseQualityProblem.jianyanren ?? '')),
          DataCell(Text(purchaseQualityProblem.zlbpsyj ?? '--')),
          DataCell(Text(purchaseQualityProblem.handleuserName ?? '')),
          // DataCell(Text(purchaseQualityProblem.causeanalysis ?? '--')),
          /**
           * 使用一个按钮，能够打开一个弹窗，显示一个历史记录的列表
           */
          _getCaurseCell(purchaseQualityProblem),
          // _getRefuceCell(purchaseQualityProblem),
          DataCell(Text(purchaseQualityProblem.effectiveverification ?? '--')),
          DataCell(Text(purchaseQualityProblem.status == '1' ? "已处理" : '提交')),
          // DataCell(Text(purchaseQualityProblem.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(purchaseQualityProblem.createDate))),
          DataCell(Text(purchaseQualityProblem.handledatetime ?? '')),
          DataCell(Text(purchaseQualityProblem.cgb ?? '')),
        ];
      },
    );
    _getSelectList();
    List<Widget> buttonBarList = [
      CryButtons.query(context, () => _query()),
      CryButtons.reset(context, () => _reset()),
      CryButtons.add(context, () => _edit(null)),
      CryButtons.edit(
          context,
          selectedList.length == 1 &&
                  selectedList[0].status != PurchaseQualityProblem.SENDED
              ? () => _edit(selectedList[0])
              : null),
      CryButtons.delete(
          context,
          selectedList.length != 0 && _checkStatus(selectedList)
              ? () => _delete(selectedList)
              : null),
      //onPressed: selectedList.length == 1 && selectedList[0].status == '1' && selectedList[0].isPush == '0'
      CryButton(
          label: "确认发出",
          iconData: Icons.drag_handle,
          onPressed: selectedList.length == 1 &&
                  selectedList[0].status ==
                      PurchaseQualityProblem
                          .CREATED && // 判断status是否有被设置过，被设置过了肯定确认过
                  selectedList[0].isPush != '1'
              ? () => _issue(selectedList[0])
              : null),
      CryButton(
          label: "退回",
          iconData: Icons.drag_handle,
          onPressed: selectedList.length == 1 &&
                  selectedList[0].status == PurchaseQualityProblem.SUBMIT_CAURSE
              ? () => _return(selectedList[0])
              : null
          // onPressed: selectedList.length == 1 &&
          //         selectedList[0].status == '1' &&
          //         selectedList[0].isPush != '1'
          //     ? () => _return(selectedList[0])
          // : null
          ),
      CryButton(
        label: "验证情况提交",
        onPressed: selectedList.length == 1 &&
                selectedList[0].status == PurchaseQualityProblem.SUBMIT_CAURSE
            ? () => _finishPurchase(selectedList[0])
            : null,
        iconData: Icons.import_export_outlined,
      ),
      CryButton(
        label: S.of(context).uploadFile,
        onPressed: selectedList.length == 1
            ? () {
                _dmsFile(selectedList[0].documentno ?? '');
              }
            : null,
        iconData: Icons.upload_file,
      ),
      CryButton(
        label: "导出质量问题反馈单",
        onPressed: () {
          /**
           * 
           * 导出excel模板，只能一次导出一份 
           * @Author: chendeji
           * @Date: 2022-05-19 14:24:10
          */
          if (selectedList != null && selectedList.length > 0) {
            Utils.generateTemplateExcel("质量问题反馈单", selectedList[0]);
          }
        },
        iconData: Icons.import_export_outlined,
      ),
      CryButton(
        label: "批量导出",
        onPressed: () => _generateExcel(),
        iconData: Icons.import_export_outlined,
      ),
    ];
    if (workshopCode != 'ZL') {
      buttonBarList = [
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: "处理",
            iconData: Icons.drag_handle,
            onPressed: selectedList.length == 1 && selectedList[0].status != '1'
                ? () => _showProblemCaurseHistory(selectedList[0])
                : null),
      ];
    }
    CryButtonBar buttonBar = CryButtonBar(children: buttonBarList);
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  // 查看反馈退回的历史记录
  _getRefuceCell(PurchaseQualityProblem purchaseQualityProblem) {
    var result = purchaseQualityProblem.resaon ?? '';
    return DataCell(
        Text(
          result,
          style: TextStyle(color: Colors.blue),
        ), onTap: () {
      if (result.isNotEmpty) {
        _showProblemRefuceHistory(purchaseQualityProblem);
      }
    });
  }

  bool _isSupplier() {
    return workshopCode != 'ZL';
  }

// 查看客户原因反馈记录
  _getCaurseCell(PurchaseQualityProblem problem) {
    var result = '';
    var isCaurseEmpty = problem.causeanalysis?.isEmpty ?? true;
    var isRectificationEmpty = problem.rectificationmeasures?.isEmpty ?? true;
    if (!isCaurseEmpty) {
      result = problem.causeanalysis ?? '';
    }
    if (!isRectificationEmpty) {
      result = '$result/${problem.rectificationmeasures}';
    }

    return DataCell(
        Text(
          result.isEmpty
              ? workshopCode != 'ZL'
                  ? '添加'
                  : ''
              : result,
          style: TextStyle(color: Colors.blue),
          overflow: TextOverflow.ellipsis,
        ), onTap: () {
      /**
                 * 这里展示一个原因分析的弹窗
                 */
      _showProblemCaurseHistory(problem);
    });
  }

  /// 显示客户原因分析全屏弹出窗口
  void _showProblemCaurseHistory(PurchaseQualityProblem problem) {
    Utils.fullscreenDialog(PurchaseQualityProblemCaurseList(
      purchaseQualityProblem: problem,
      workCode: workshopCode,
    ));
  }

  void _showProblemRefuceHistory(PurchaseQualityProblem problem) {
    var empty = problem.resaon?.isEmpty ?? true;
    if (empty) {
      return;
    }
    Utils.fullscreenDialog(PurchaseQualityProblemRefuseList(
      purchaseQualityProblem: problem,
    ));
  }

  bool _checkStatus(List<PurchaseQualityProblem> selectedList) {
    for (var i = 0; i < selectedList.length; i++) {
      if (selectedList[i].status == '1') return false;
    }
    return true;
  }

  _edit(PurchaseQualityProblem? purchaseQualityProblem,
      {isHandle: false, isEditable: true}) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseQualityProblemEdit(
          purchaseQualityProblem: purchaseQualityProblem,
          isHandle: isHandle,
          isEditable: isEditable,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _reset() {
    purchaseQualityProblem = PurchaseQualityProblem();
    purchaseQualityProblem.createDateStart = Utils.getDate();
    purchaseQualityProblem.createDateEnd = Utils.getDate();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (workshopCode == 'ZL') {
      purchaseQualityProblem.isPush = '0';
    } else {
      purchaseQualityProblem.isPush = '1';
    }
    ResponseBodyApi responseBodyApi =
        await PurchaseQualityProblemOdooApi.page(data: {
      "page": page,
      "domainList": purchaseQualityProblem.toDomainList(),
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _issue(PurchaseQualityProblem purchaseQualityProblem) async {
    cryConfirm(context, '是否确认发出', (context) async {
      purchaseQualityProblem.isPush = '1';
      purchaseQualityProblem.status = PurchaseQualityProblem.SENDED;
      /**
       * 
       * 获取当前的时间，更新到后端 
       * @Author: chendeji
       * @Date: 2022-05-19 17:08:26
      */
      purchaseQualityProblem.comfirmTime =
          DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());

      var result = await PurchaseQualityProblemOdooApi.saveOrUpdate(
          purchaseQualityProblem.toOdooMap());
      if (result.success!) {
        _loadData();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _dmsFile(String documentno) {
    Utils.fullscreenDialog(DmsFileList(
      udtTbDocmentstock: null,
      saleBidProject: null,
      documentno: documentno,
      uploadFileType: '*',
    ));
  }

  _return(PurchaseQualityProblem purchaseQualityProblem) async {
    /**
     * 
     * 弹窗显示提示输入退回理由，点击提交，显示一个确认按钮
     * 
     * @Author: chendeji
     * @Date: 2022-05-18 16:18:02
    */
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: QualityCaurseRefuse(
          title: '新增退回',
          subTitle: '退回原因',
          hint: '请输入退回的原因',
          errorToast: '请填写退回原因',
        ),
      ),
    ).then((v) async {
      if (v != null) {
        purchaseQualityProblem.isPush = '1';
        purchaseQualityProblem.status = PurchaseQualityProblem.REFUSE;

        var result = await PurchaseQualityProblemOdooApi.saveOrUpdate(
            purchaseQualityProblem.toOdooMap());
        // 新增退回历史记录
        var addRefuseResult = await PurchaseQualityProblemOdooApi.submitRefuse({
          'problem_id': '${purchaseQualityProblem.id}',
          'resaon': v['content'],
        });
        if (result.success! && addRefuseResult.success!) {
          _loadData();
          CryUtils.message(S.of(Cry.context).success);
        }
      }
    });
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<PurchaseQualityProblem> resultList = [];
    ResponseBodyApi responseBodyApi =
        await PurchaseQualityProblemOdooApi.findAll(data: {
      "domainList": purchaseQualityProblem.toDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data.map<PurchaseQualityProblem>((e) {
        return PurchaseQualityProblem.fromMap(e);
      }).toList();
    }
    return resultList;
  }

  ///
  ///提交反馈单的结单操作，然后更新反馈单的结单结果
  ///@Author: chendeji
  ///@Date: 2022-05-21 14:18:45
  ///
  _finishPurchase(PurchaseQualityProblem purchaseQualityProblem) {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: QualityCaurseRefuse(
          title: '提交验证',
          subTitle: '验证情况',
          hint: '请填入最后验收情况描述',
          errorToast: '请填入验收具体内容',
        ),
      ),
    ).then((v) async {
      if (v != null) {
        purchaseQualityProblem.isPush = '0';
        purchaseQualityProblem.effectiveverification = v['content'];

        var result = await PurchaseQualityProblemOdooApi.saveOrUpdate(
            purchaseQualityProblem.toOdooMap());
        if (result.success!) {
          _loadData();
          CryUtils.message(S.of(Cry.context).success);
        }
      }
    });
  }

  _generateExcel() async {
    List<PurchaseQualityProblem> selectedList = this.selectedList;
    if (selectedList == null || selectedList.length == 0) {
      Fluttertoast.showToast(msg: S.current.selectOneProblemExport);
      return;
    }

    // if (selectedList.length == 1) {
    //   // createExcelByTemplate(selectedList[0], "质量问题反馈单");
    //   Utils.generateTemplateExcel("质量问题反馈单", selectedList[0]);
    // } else {
    List<Map> map = [
      {
        'name': 'serialnumber',
        'label': '流水号',
        'columnWidth': 15.0,
      },
      {
        'name': 'bhx',
        'label': '文档号',
        'columnWidth': 15.0,
      },
      {
        'name': 'productName',
        'label': '产品名称',
        'columnWidth': 12.0,
      },
      {
        'name': 'spec',
        'label': '规格型号',
        'columnWidth': 19.0,
      },
      {
        'name': 'supplierName',
        'label': '供应单位',
        'columnWidth': 12.0,
      },
      {
        'name': 'jcrq',
        'label': '检测日期',
        'columnWidth': 12.0,
      },
      {
        'name': 'instockqty',
        'label': '来料数量',
        'columnWidth': 12.0,
      },
      {
        'name': 'checkqty',
        'label': '抽检数量',
        'columnWidth': 14.0,
      },
      {
        'name': 'unqualifiedqty',
        'label': '不合格数量',
        'columnWidth': 14.0,
      },
      {
        'name': 'questiondescription',
        'label': '问题描述',
        'columnWidth': 12.0,
      },
      {
        'name': 'jianyanren',
        'label': '检验人',
        'columnWidth': 10.0,
      },
      {
        'name': 'zlbpsyj',
        'label': '处理方式',
        'columnWidth': 12.0,
      },
      {
        'name': 'handleuserName',
        'label': '处理人',
        'columnWidth': 10.0,
      },
      {
        'name': 'causeanalysis',
        'label': '客户原因分析',
        'columnWidth': 18.0,
      },
      {
        'name': 'rectificationmeasures',
        'label': '改进措施',
        'columnWidth': 12.0,
      },
      {
        'name': 'effectiveverification',
        'label': '跟踪情况验证',
        'columnWidth': 18.0,
      },
      {
        'name': 'status',
        'label': '状态',
        'columnWidth': 10.0,
      },
      // {
      //   'name': 'createName',
      //   'label': '创建人',
      //   'columnWidth': 10.0,
      // },
      {
        'name': 'createDate',
        'label': '创建时间',
        'columnWidth': 21.0,
      },

      {
        'name': 'handledatetime',
        'label': '处理时间',
        'columnWidth': 21.0,
      },
      {
        'name': 'cgb',
        'label': '采购员',
        'columnWidth': 10.0,
      },
    ];
    Utils.generateExcel(
        fileName: "质量问题反馈单", configure: map, data: selectedList);
    // }
  }

  _delete(List<PurchaseQualityProblem> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await PurchaseQualityProblemOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseQualityProblemDialog(),
      ),
    ).then((v) {
      if (v != null) {
        purchaseQualityProblem = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<PurchaseQualityProblem>(
                (e) => PurchaseQualityProblem.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }

  getDateDiffDayCount(
      PurchaseQualityProblem purchaseQualityProblem, DateFormat formator) {
    int dealDayCount = 0;
    if (purchaseQualityProblem.comfirmTime!.isNotEmpty) {
      if (purchaseQualityProblem.lastSupOpTime!.isNotEmpty &&
          purchaseQualityProblem.lastRefuseTime!.isEmpty) {
        var opTime = Utils.timeUTC(purchaseQualityProblem.lastSupOpTime);
        var comfirmTime = purchaseQualityProblem.comfirmTime;
        var opDate = formator.parse(opTime);
        var comfirmDate = formator.parse(comfirmTime!);
        var diff = opDate.difference(comfirmDate);
        dealDayCount = diff.inDays;
      } else if (purchaseQualityProblem.lastSupOpTime!.isNotEmpty &&
          purchaseQualityProblem.lastRefuseTime!.isNotEmpty) {
        var opTime = Utils.timeUTC(purchaseQualityProblem.lastSupOpTime);
        var refuseTime = Utils.timeUTC(purchaseQualityProblem.lastRefuseTime);
        var opDate = formator.parse(opTime);
        var refuseDate = formator.parse(refuseTime!);
        var diff = opDate.difference(refuseDate);
        dealDayCount = diff.inDays;
      }
    }
    return dealDayCount;
  }

  // Future<void> createExcelByTemplate(
  //     PurchaseQualityProblem problem, String fileName) async {
  //   /**
  //    *
  //    * 使用本地的excel模板对齐某些空格处的内容进行修改
  //    *
  //    * @Author: chendeji
  //    * @Date: 2022-05-18 10:03:49
  //   */

  //   ByteData data =
  //       await rootBundle.load("assets/template/quality_excel_template.xlsx");
  //   var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
  //   var excel = Excel.decodeBytes(bytes);
  //   var cellStyle = CellStyle(textWrapping: TextWrapping.WrapText);

  //   // 开始将数据填入表格的空位中，然后创建生成表格，下载
  //   Sheet sheetObject = excel['Table 1'];
  //   sheetObject.cell(CellIndex.indexByString("B3")).value =
  //       problem.serialnumber; // 流水号
  //   sheetObject.cell(CellIndex.indexByString("B4")).value = problem.spec; // 型号
  //   sheetObject.cell(CellIndex.indexByString("B5")).value =
  //       problem.instockdate; // 来料日期
  //   sheetObject.cell(CellIndex.indexByString("B6")).value =
  //       problem.checkqty; // 抽样数量
  //   sheetObject.cell(CellIndex.indexByString("D3")).value =
  //       problem.supplierName; // 供应商名称
  //   sheetObject.cell(CellIndex.indexByString("D4")).value =
  //       problem.productName; // 产品名称
  //   sheetObject.cell(CellIndex.indexByString("D5")).value =
  //       problem.instockqty; // 来料数量
  //   sheetObject.cell(CellIndex.indexByString("D6"))
  //     ..value = problem.unqualifiedqty; // 不合格数量
  //   sheetObject.cell(CellIndex.indexByString("B7"))
  //     ..cellStyle = cellStyle
  //     ..value = '${problem.questiondescription}'; // 问题描述
  //   sheetObject.cell(CellIndex.indexByString("B8"))
  //     ..cellStyle = cellStyle
  //     ..value = '${problem.zlbpsyj}'; // 处理方式
  //   sheetObject.cell(CellIndex.indexByString("B9"))
  //     ..cellStyle = cellStyle
  //     ..value = '${problem.causeanalysis}'; // 供应商原因分析：
  //   sheetObject.cell(CellIndex.indexByString("B10"))
  //     ..cellStyle = cellStyle
  //     ..value = '${problem.rectificationmeasures}'; // 改进措施：
  //   sheetObject.cell(CellIndex.indexByString("B11"))
  //     ..cellStyle = cellStyle
  //     ..value = '${problem.effectiveverification}'; // 改进措施：

  //   excel.save(fileName: "$fileName.xlsx");
  // }
}

/// 填写退回理由弹窗
// ignore: must_be_immutable
class QualityCaurseRefuse extends StatelessWidget {
  QualityCaurseRefuse({
    required this.title,
    required this.subTitle,
    required this.hint,
    required this.errorToast,
    Key? key,
  }) : super(key: key);

  String title;
  String subTitle;
  String hint;
  String errorToast;

  var reason = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 650,
      height: 650,
      child: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Column(
          children: [
            Container(
              margin: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    subTitle,
                    style: TextStyle(color: Colors.blue),
                  ),
                  Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        border: Border.all(width: 1, color: Colors.blue)),
                    child: TextField(
                      minLines: 5,
                      maxLines: 5,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                          hintStyle: TextStyle(color: Colors.blueGrey)),
                      controller: reason,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CryButton(
                  label: "提交",
                  onPressed: () {
                    if (reason.text.isNotEmpty) {
                      Navigator.pop(context, {
                        'content': reason.text,
                      });
                    } else {
                      Fluttertoast.showToast(msg: errorToast);
                    }
                  },
                  iconData: Icons.add,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
